﻿using Bot.Dynamics365.Extension;
using Bot.Dynamics365.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Dynamics365
{
    public class TokenService : ITokenService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<TokenService> _logger;

        public TokenService(IHttpClientFactory httpClientFactory,
            ILogger<TokenService> logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        public async Task<string> GetAccessTokenAsync(AzureAD azure)
        {
            var url = $"https://login.microsoftonline.com/{azure.TenantID}/oauth2/v2.0/token";
            var input = JsonConvert.SerializeObject(new
            {
                url,
                azure,
            });
            _logger.LogDebug($"GetAccessTokenAsync input:{input}");

            var request = Utils.BuildHttpRequestMessage(url, Enum.EnumHttpMethod.Post);
            request.AddForm(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("grant_type", "client_credentials"),
                new KeyValuePair<string, string>("client_id", azure.AppID),
                new KeyValuePair<string, string>("client_secret", azure.AppSecret),
                new KeyValuePair<string, string>("scope", $"{azure.InstanceUrl}/.default"),
            });
            var httpResponse = await _httpClientFactory.SendAsync(request);
            _logger.LogDebug($"GetAccessTokenAsync response:{JsonConvert.SerializeObject(httpResponse)}");
            if (httpResponse.IsSuccessStatusCode)
            {
                return JsonConvert.DeserializeObject<AccessTokenResponse>(httpResponse.Response).access_token;
            }
            else
            {
                throw new Exception(httpResponse.Response);
            }
        }
    }
}
